﻿//div_Widgets
//NewTab.Element_Cell1 = eCell1;
//NewTab.Element_Cell2 = eCell2;
//NewTab.Element_Cell3 = eCell3;

_Tab = function(element)
{
   this.id = element.id;
   this.obj = element;
   this.Element_Widgets = null;
   this.loaded = false;
   this.Widgets = new Array();
   
   if(element.Widgets)
   {
      for(var i=0;i<element.Widgets.length;i++)
      {
         this.Widgets.push(new _Widget(element.Widgets[i], this));
      }
   }
}

_Tab.prototype =
{
    FindWidget: function(widgetId) {
        for (var i = 0; i < this.Widgets.length; i++) {
            if (this.Widgets[i].id == widgetId)
                return this.Widgets[i];
        }

        return null;
    },

    hasRequiredTabPermission: function(Permission) {
        var Tab = this;
        for (var i = 0; i < Tab.obj.AccessLevel.length; i++) {
            if (Tab.obj.AccessLevel[i] == Permission || Tab.obj.AccessLevel[i] == TabAccessLevel.Owner)
                return true;
        }
        return false;
    },

    TellMePermission: function() {
        var Tab = this;
        var Permission = "You have the following permission for this tab:\n";

        for (var i = 0; i < Tab.obj.AccessLevel.length; i++) {
            Permission += "- " + GetAccessLevelStr(Tab.obj.AccessLevel[i]) + "\n";
        }

        alert(Permission);
    },

    Dispose: function() {
        this.loaded = false;

        for (var i = 0; i < this.Widgets.length; i++)
            if (this.Widgets[i].Dispose)
            this.Widgets[i].Dispose();

        this.Widgets = new Array();

        var IDToRemove = "WTab_" + this.id;

        //loop thru all the childnodes in the widget div and remove this id if it exists
        if (div_Widgets.childNodes) {
            var ttl = div_Widgets.childNodes.length;
            for (var i = 0; i < ttl; i++) {
                var e = div_Widgets.childNodes[i];
                var eID = "";
                if (e && e.id)
                    eID = e.id;

                if (eID.length >= IDToRemove.length) {
                    if (eID.substring(0, IDToRemove.length) == IDToRemove) {
                        div_Widgets.removeChild(e);
                        ttl--;
                        i--;
                    }
                }
            }
        }
    },

    Render: function() {
        this.Dispose();
        if (this.obj.InnerHTML.length > 0) {
            div_WidgetProgress.style.display = "none";
            var TabInnerHTML = this.obj.InnerHTML;
            TabInnerHTML = TabInnerHTML.replace("WTab", "WTab_" + this.id);
            TabInnerHTML = TabInnerHTML.replace("td_1", "c" + this.id + "_1");
            TabInnerHTML = TabInnerHTML.replace("td_2", "c" + this.id + "_2");
            TabInnerHTML = TabInnerHTML.replace("td_3", "c" + this.id + "_3");
            TabInnerHTML = TabInnerHTML.replace("td_4", "c" + this.id + "_4");
            div_Widgets.innerHTML += TabInnerHTML;
            eWidget = document.getElementById("WTab_" + this.id);
            this.Element_Cell1 = document.getElementById("c" + this.id + "_1");
            this.Element_Cell2 = document.getElementById("c" + this.id + "_2");
            this.Element_Cell3 = document.getElementById("c" + this.id + "_3");
            this.Element_Cell4 = document.getElementById("c" + this.id + "_4");
            return eWidget;
        }
        else {
            eWidget = document.createElement("div");
            eWidget.id = "WTab_" + this.id;
            setElementToAjaxLoading(eWidget, "<div align='center'>", "</div>");
            eWidget.appendChild(document.createTextNode(this.id + " : " + this.obj.Title));
            div_Widgets.appendChild(eWidget);

            //Generate the widgets
            var eTbl = document.createElement("table");
            eTbl.setAttribute("width", "100%");
            eTbl.setAttribute("cellpadding", "0");
            eTbl.setAttribute("cellspacing", "0");
            eTbl.setAttribute("height", "250px");
            eTbl.setAttribute("border", "0");

            var eTBody = document.createElement("tbody");

            var eRow = document.createElement("tr");
            eRow.setAttribute("valign", "top");

            var eCell1 = document.createElement("td");
            eCell1.id = "c" + this.id + "_1";
            eCell1.setAttribute("width", this.obj.PanelWidth_1 + "%");
            eCell1.style.position = "relative";

            var eCell2 = document.createElement("td");
            eCell2.id = "c" + this.id + "_2";
            if (this.obj.PanelWidth_2 > 0) {
                eCell2.setAttribute("width", this.obj.PanelWidth_2 + "%");
            }
            else {
                eCell2.setAttribute("width", "0");
                eCell2.style.display = "none";
            }

            eCell2.style.position = "relative";

            var eCell3 = document.createElement("td");
            eCell3.id = "c" + this.id + "_3";
            if (this.obj.PanelWidth_3 > 0) {
                eCell3.setAttribute("width", this.obj.PanelWidth_3 + "%");
            }
            else {
                eCell3.setAttribute("width", "0");
                eCell3.style.display = "none";
            }
            eCell3.style.position = "relative";

            eRow.appendChild(eCell1);
            eRow.appendChild(eCell2);
            eRow.appendChild(eCell3);
            eTBody.appendChild(eRow);
            eTbl.appendChild(eTBody);
            removeChildNodes(eWidget);
            eWidget.appendChild(eTbl);
            this.Element_Cell1 = eCell1;
            this.Element_Cell2 = eCell2;
            this.Element_Cell3 = eCell3;
            return eWidget;
        }

        return null;
    }
}

_myTabs = function()
{
   this.Tabs = new Array();
   this.ActiveTabID = -1;
}

_myTabs.prototype =
{
    onTabChange: function() {
        tab_width = 0;
        for (var i = 0; i < div_TabList.childNodes.length; i++) {
            var e = div_TabList.childNodes[i];
            if (e) {
                WriteHistory(e.id + ":" + e.clientWidth + ":" + e.offsetWidth);
                tab_width += getElementWidth(e) + 5;
            }
        }
        var holderWidth = f_clientWidth() - 200;
        if (holderWidth < tab_width) {
            $show("tab_L");
            $show("tab_R");
            div_tabHolder.style.width = holderWidth + "px";
            div_TabList.style.width = tab_width + "px";

            //after doing this, i need to find out where the activetab is and move to there
            var CurrentTab = this.GetCurrentTab();
            if (CurrentTab && CurrentTab.Element_Main) {
                var E_M = CurrentTab.Element_Main;
                var NewMarginLeft = parseInt(E_M.offsetLeft + getElementWidth(E_M)) - parseInt(div_tabHolder.style.width);
                WriteHistory(NewMarginLeft + ":" + CurrentTab.Element_Main.offsetLeft + ":" + div_tabHolder.style.width);
                if (NewMarginLeft > 0) {
                    div_TabList.style.marginLeft = (-NewMarginLeft) + "px";
                }
            }
        }
        else {
            $hide("tab_L");
            $hide("tab_R");
            if (is_ie) {
                div_tabHolder.style.width = tab_width + "px";
            }
            else {
                div_tabHolder.style.width = "";
            }
            div_TabList.style.marginLeft = "0px";
        }
        WriteHistory("Total Width:" + tab_width + ":" + holderWidth);
    },

    TellMePermission: function(TabId) {
        var Tab = this.FindTab(TabId);
        if (Tab)
            Tab.TellMePermission();
    },

    hasRequiredTabPermission: function(Tab, Permission) {
        if (Tab == null) {
            Tab = this.GetCurrentTab();
        }

        return Tab.hasRequiredTabPermission(Permission);
    },

    SaveTitle: function() {
        var CurrentTab = this.GetCurrentTab();
        if (this.hasRequiredTabPermission(CurrentTab, TabAccessLevel.Tab_EditName)) {
            WriteHistory("SaveTitle");
            if (CurrentTab) {
                if (CurrentTab.Element_Input.value != CurrentTab.obj.Title) {
                    CurrentTab.obj.Title = CurrentTab.Element_Input.value;
                    CurrentTab.Element_Txt.innerHTML = CurrentTab.obj.Title;

                    JSON.Tab_SaveTitle(CurrentTab.obj.Title, this.ActiveTabID);
                }

                CurrentTab.Element_Input.style.display = "none";
                CurrentTab.Element_Txt.style.display = "";
                CurrentTab.Element_Arrow.style.display = "";
                this.onTabChange();
            }
        }
        else {
            alert("You do not have permission to edit the tab title");
        }
    },

    ResetTab: function(TabId) {
        this.RefreshTab(TabId);
    },

    RefreshTab: function(TabId) {
        var Tab = this.FindTab(TabId);
        $hide("menu_" + Tab.id);
        Tab.Dispose();
        JSON.Tab_Refresh(TabId, Function.createDelegate(this, this.RefreshComplete));
    },

    RefreshComplete: function(obj) {
        var theTab = this.FindTab(obj.id);
        theTab.obj = obj;
        this.SwitchActiveTab(theTab.id);
    },

    ReloadCurrentTab: function(intVal) {
        if (intVal < 1) {
        }
        else {
            var Tab = this.FindTab(intVal);
            Tab.Dispose();

            if (this.ActiveTabID == intVal) {
                alert("This page has been changed, click ok to refresh the page");
                this.SwitchActiveTab(intVal);
            }
        }
    },


    GenerateTab: function(Tab) {
        WriteHistory("GenerateTab" + Tab.id);
        //Generate the Tab Tab
        var eTab = document.createElement("li");
        eTab.setAttribute("id", "p_" + Tab.id);

        //Create the text node
        var eTxt = document.createElement("span");
        eTxt.setAttribute("id", "t_" + Tab.id);
        eTxt.innerHTML = Tab.obj.Title;
        var f1 = "myTabs.SwitchActiveTab(" + Tab.id + ")";
        eTxt.onclick = function() { eval(f1); };
        //DoTip(eTxt, "Click to switch to this Tab");
        eTab.appendChild(eTxt);

        //Create the menu
        var eDiv = document.createElement("div");
        eDiv.id = "menu_" + Tab.id;
        var eDIV_M1 = "";

        if (Tab.hasRequiredTabPermission(TabAccessLevel.Tab_Share)) {
            eDIV_M1 += "<li><a onclick='myTabs.ShareTab(" + Tab.id + ");'>Share Tab</a></li>";
        }

        eDIV_M1 += "<li><a onclick='myTabs.DeleteTab(" + Tab.id + ");'>Delete Tab</a></li>";

        eDIV_M1 += "<li><a onclick='myTabs.TellMePermission(" + Tab.id + ");'>Tab Permissions</a></li>";

        eDIV_M1 += "<li><a onclick='myTabs.RefreshTab(" + Tab.id + ");'>Refresh Tab</a></li>";
        //var eDIV_M3 = "Share Page";
        eDiv.innerHTML = "<ul class='DDMenu'>" + eDIV_M1 + "</ul>";
        eDiv.className = "DropDownMenu";
        div_Widgets.appendChild(eDiv);

        //Create the drop down arrow element
        var eArrow = document.createElement("a");
        eArrow.setAttribute("id", "a_" + Tab.id);
        eArrow.className = "tab_arrow";
        eArrow.width = 10;
        eArrow.height = 10;
        eArrow.onclick = expand;
        if (is_ie) {
            eArrow.href = "javascript:void(0);";
            eArrow.innerHTML = "<img src='/images/pixel.gif' border='0' width='1px' height='10px' />";
        }
        eArrow.onmouseout = function() { collapse(this.id); };
        eArrow.setAttribute("border", 0);
        eTab.appendChild(eArrow);

        if (this.hasRequiredTabPermission(Tab, TabAccessLevel.Tab_EditName)) {
            //only create the textbox if they have permission to edit the textbox
            var eInp = document.createElement("input");
            eInp.setAttribute("id", "i_" + Tab.id);
            eInp.onblur = function() { myTabs.SaveTitle(); };
            if (is_ie)
                eInp.onkeypress = function() { if (event.keyCode == 13) { myTabs.SaveTitle(); event.keyCode = 0; return false; } };
            else
                eInp.onkeypress = function(event) { if (event.keyCode == 13) { myTabs.SaveTitle(); return false; } };

            eInp.value = Tab.obj.Title;
            eInp.style.display = "none";
            eTab.appendChild(eInp);
        }

        eTab.className = "tab inactivetab";
        div_TabList.appendChild(eTab);
        installScript("Menu_AddTarget('a_" + Tab.id + "', '" + eDiv.id + "');");

        Tab.Element_Txt = eTxt;

        if (this.hasRequiredTabPermission(Tab, TabAccessLevel.Tab_EditName)) {
            Tab.Element_Input = eInp;
        }
        else {
            Tab.Element_Input = null;
        }

        Tab.Element_Main = eTab;
        Tab.Element_Arrow = eArrow;
    },

    GetCurrentTab: function() {
        return this.FindTab(this.ActiveTabID);
    },

    SwitchActiveTab: function(TabId) {
        WriteHistory("SwitchActiveTab" + TabId);
        //Switch the active Tab to the Tabid
        var CurrentTab = this.GetCurrentTab();
        var NewTab = this.FindTab(TabId);

        if (NewTab != null) {
            if (CurrentTab != null) {
                var f1 = "myTabs.SwitchActiveTab(" + CurrentTab.id + ")";
                CurrentTab.Element_Txt.onclick = function() { eval(f1); };

                //Hide the input
                if (CurrentTab.Element_Input) {
                    CurrentTab.Element_Input.style.display = "none";
                }

                CurrentTab.Element_Txt.style.display = "";
                CurrentTab.Element_Arrow.style.display = "";
                CurrentTab.Element_Main.className = "tab inactivetab";

                //DoTip(CurrentTab, "Click to switch to this Tab");
                //DoTip(CurrentTab.Element_Txt, "Click to switch to this Tab");

                if (CurrentTab.Element_Widgets) {
                    CurrentTab.Element_Widgets.style.display = "none";
                }

                //Update DB with new ActiveTab
                JSON.User_UpdateActiveTab(NewTab.id);
            }

            if (this.hasRequiredTabPermission(NewTab, TabAccessLevel.Tab_ChangeLayout)) {
                $show('banner_modifyLayout', 'NONE');
            }
            else {
                $hide('banner_modifyLayout');
            }

            if (this.hasRequiredTabPermission(NewTab, TabAccessLevel.Tab_AddWidgets)) {
                $show('banner_addWidget', 'NONE');
                $show('banner_sep1', 'NONE');
            }
            else {
                $hide('banner_addWidget');
                $hide('banner_sep1');
            }

            //If user has permission to edit the tab, set the relevant onclick event
            if (this.hasRequiredTabPermission(NewTab, TabAccessLevel.Tab_EditName)) {
                var f2 = "$show('" + NewTab.Element_Input.id + "','inline',true);$hide('" + NewTab.Element_Txt.id + "');$hide('" + NewTab.Element_Arrow.id + "');";
                NewTab.Element_Txt.onclick = function() { eval(f2); };
                NewTab.Element_Main.className = "tab activetab";
                //DoTip(NewTab, "Click to change title for this");         
                //DoTip(NewTab.Element_Txt, "Click to change title for this");         
            }
            else {
                NewTab.Element_Txt.onclick = null;
                NewTab.Element_Main.className = "tab activetab";
                //DoTip(NewTab, "You do not have permission to change the title for this tab");
                //DoTip(NewTab.Element_Txt, "You do not have permission to change the title for this tab");
            }

            this.ActiveTabID = TabId;

            //update the menu add to tab text
            WriteHistory("Switching WidgetInfo");
            var eMenu = $get("MenuWidgetAddWidgetBtn");
            if (eMenu) {
                var TabTitle = NewTab.obj.Title;
                if (TabTitle) {
                    if (TabTitle.length > 10) {
                        TabTitle = TabTitle.substring(0, 8) + "..";
                    }

                    TabTitle = "\"" + TabTitle + "\" Tab";
                }
                else {
                    TabTitle = "Tab";
                }
                eMenu.value = "Add To " + TabTitle;
            }

            if (NewTab.loaded && NewTab.Element_Widgets) {
                WriteHistory("Historical Page");
                //if this tab is loaded before, just show the div
                NewTab.Element_Widgets.style.display = "block";
                HideNoWidget();
            }
            else {
                WriteHistory("New Page");

                //show the progress bar during loading
                div_WidgetProgress.style.display = "";

                //hide the no widget div
                HideNoWidget();
                var eWidget = NewTab.Render();

                myWidgets.GenerateForTab(NewTab);
                setTimeout("myTabs.LoadWidgetScripts()", 500);

                //add this div to the list of divs
                NewTab.Element_Widgets = eWidget;
                NewTab.Element_Widgets.style.display = "block";
                NewTab.loaded = true;

                //Enable widget drag and drop for all columns first, just in case..
                //but only if user has the permission
                if (this.hasRequiredTabPermission(NewTab, TabAccessLevel.Widget_Reorder)) {
                    this.EnableWidgetDragDrop(NewTab, 1);
                    this.EnableWidgetDragDrop(NewTab, 2);
                    this.EnableWidgetDragDrop(NewTab, 3);
                    if (NewTab.Element_Cell4) {
                        this.EnableWidgetDragDrop(NewTab, 4);
                    }
                }
            }
        }
        else {
            alert("Unable to switch tabs\n" + TabId);
        }
        this.onTabChange();
    },

    LoadWidgetScripts: function() {
        WriteHistory("LoadWidgetScripts");
        var Tab = this.GetCurrentTab();

        for (var i = 0; i < Tab.Widgets.length; i++) {
            var theWidget = Tab.Widgets[i];
            if (!Tab.Widgets[i].loaded) {
                WriteHistory("Widget #" + Tab.Widgets[i].id + " not loaded");

                if (this.DoLoad_Idx)
                    this.DoLoad_Idx++;
                else
                    this.DoLoad_Idx = 1;

                if (this.DoLoad_Idx < 10)
                    setTimeout("myTabs.LoadWidgetScripts()", 1000);

                return;
            }
        }

        JSScripts.RunAllScripts();
    },

    AddNewTab: function() {
        //Adds a new Tab

        //JSON --> Get the new Tabid
        JSON.Tab_Add(Function.createDelegate(this, this.onAddNewTabSuccess));
    },

    onAddNewTabSuccess: function(obj) {
        if (obj) {
            var Tab = new _Tab(obj);
            this.Tabs.push(Tab);

            //GUI - Generate the new Tab
            this.GenerateTab(Tab);

            //Allow for sorting
            this.EnableDragDrop();

            this.onTabChange();
        }
    },

    ShareTab: function(TabId) {
        var Tab = myTabs.FindTab(TabId);
        if (this.hasRequiredTabPermission(Tab, TabAccessLevel.Tab_Share)) {
            winopen("/tab_modifyshare.aspx?id=" + TabId, 450, 400);
        }
        else {
            alert("You do not have permission to perform this action");
        }
    },

    //Delete this tab
    DeleteTab: function(TabId) {
        var Tab = myTabs.FindTab(TabId);
        if (this.Tabs.length < 2) {
            alert("There needs to be at least one Tab on your workspace");
        }
        else {
            $hide("menu_" + Tab.id);
            if (confirm("Are you sure you want to delete the " + Tab.obj.Title.replace("\"", "\\\"") + " Tab?")) {
                var proceed = false;
                if (confirm("Once you delete this tab, there is no way to recover the contents of this tab. \nAre you really sure you want to delete the " + Tab.obj.Title.replace("\"", "\\\"") + " Tab?")) {
                    if (Tab.hasRequiredTabPermission(TabAccessLevel.Tab_Delete)) {
                        //if have delete permission, double confirm
                        proceed = true;
                    }
                    else {
                        //otherwise just proceed, since is just removing the link
                        proceed = true;
                    }
                }

                if (proceed) {
                    var elementid = -1;
                    for (var i = 0; i < this.Tabs.length; i++) {
                        if (this.Tabs[i].id == TabId) {
                            elementid = i;
                            break;
                        }
                    }

                    if (elementid > -1) {
                        //Remove the element from the Array
                        var Tab = this.Tabs[elementid];

                        //GUI - Remove the Tab Div
                        div_TabList.removeChild(Tab.Element_Main);

                        if (Tab.Element_Widgets)
                            div_Widgets.removeChild(Tab.Element_Widgets);

                        //DB Update - Remove Tab from list, reorder and update active Tab
                        JSON.Tab_Delete(Tab.id, this.ActiveTabID);

                        if (Tab.id == this.ActiveTabID) {
                            //GUI - If Tab is active Tab, change active Tab to another Tab
                            if (elementid == 0) {
                                //if is first element, switch to the next element
                                this.SwitchActiveTab(this.Tabs[elementid + 1].id);
                            }
                            else {
                                this.SwitchActiveTab(this.Tabs[elementid - 1].id);
                            }
                        }

                        //Remove the Tab object from the array
                        this.Tabs.splice(elementid, 1);
                    }
                }
            }
        }
        this.onTabChange();
    },

    FindTab: function(Tabid) {
        for (var i = 0; i < this.Tabs.length; i++) {
            if (this.Tabs[i].id == Tabid)
                return this.Tabs[i];
        }

        return null;
    },

    FirstLoad: function() {
        JSON.UserFirstLoad(Function.createDelegate(this, this.onContentLoad));
    },

    onContentLoad: function(obj) {
        if (obj) {
            WriteHistory("OnContentLoad" + div_TabList);
            //remove all child nodes from the tab list element
            if (div_TabList.childNodes.length > 0)
                removeChildNodes(div_TabList);

            //DB - Get List of Tabs
            this.ActiveTabID = obj.ActiveTabID;

            //GUI - Load all the Tabs
            var eTabs = obj.Tabs;
            this.Tabs = new Array();
            for (var i = 0; i < eTabs.length; i++) {
                var Tab = new _Tab(eTabs[i]);
                this.Tabs.push(Tab);
                this.GenerateTab(Tab);
            }

            this.SwitchActiveTab(this.ActiveTabID);
            this.EnableDragDrop();
        }
        else {
            alert("We are unable to get the list of Tabs for your account");
        }
    },

    ChangeHtmlLayout: function(textareaid) {
        var CustomHTML = document.getElementById(textareaid);

    },

    ChangeLayout_Complete: function() {
        var Tab = this.GetCurrentTab();
        this.RefreshTab(Tab.id);
    },

    ChangeLayout: function(c1, c2, c3, c4, innerHTML) {
        var Tab = this.GetCurrentTab();
        if (innerHTML == null)
            innerHTML = document.getElementById("layout_innerhtml").value;

        if (this.hasRequiredTabPermission(Tab, TabAccessLevel.Tab_ChangeLayout)) {
            if (innerHTML.length > 0) {
                Tab.obj.InnerHTML = innerHTML;
                JSON.Tab_Resize(Tab.id, 0, 0, 0, 0, innerHTML, Function.createDelegate(this, this.ChangeLayout_Complete));
            }
            else {
                //IE has a very interesting rendering, if the table cell has 0 width, space is still allocated for it
                // the only way is to hide the cell
                Tab.Element_Cell1.setAttribute("width", c1 + "%");
                if (c2 > 0) {
                    Tab.Element_Cell2.style.display = "";
                    Tab.Element_Cell2.setAttribute("width", c2 + "%");
                }
                else {
                    Tab.Element_Cell2.style.display = "none";
                    Tab.Element_Cell2.setAttribute("width", "0");
                }

                if (c3 > 0) {
                    Tab.Element_Cell3.style.display = "";
                    Tab.Element_Cell3.setAttribute("width", c3 + "%");
                }
                else {
                    Tab.Element_Cell3.style.display = "none";
                    Tab.Element_Cell3.setAttribute("width", "0");
                }

                if (c4 > 0 && Tab.Element_Cell4) {
                    Tab.Element_Cell4.style.display = "";
                    Tab.Element_Cell4.setAttribute("width", c4 + "%");
                }
                else {
                    Tab.Element_Cell4.style.display = "none";
                    Tab.Element_Cell4.setAttribute("width", "0");
                }

                Tab.obj.PanelWidth_1 = c1;
                Tab.obj.PanelWidth_2 = c2;
                Tab.obj.PanelWidth_3 = c3;
                Tab.obj.PanelWidth_4 = c4;
                JSON.Tab_Resize(Tab.id, c1, c2, c3, c4, "");

                //need to move the widgets?
                if (c2 == 0 || c3 == 0 || c4 == 0) {
                    var c2To = -1;
                    var c3To = -1;
                    var c4To = -1;

                    if (c4 == 0) {
                        c4To = 3;
                        if (c3 == 0) {
                            c4To = 2;
                            if (c2 == 0)
                                c4To = 1;
                        }
                    }
                    //check column 3 move to which column
                    if (c3 == 0) {
                        c3To = 2;
                        if (c2 == 0)
                            c3To = 1;
                    }

                    //set column 2 move to column 1
                    if (c2 == 0) {
                        c2To = 1;
                    }

                    //Sort the widgets first      
                    myWidgets.SortWidgetArray(Tab);

                    //Get the last order for each column
                    var theWidgets = Tab.Widgets;
                    var c1LastOrder = 0;
                    var c2LastOrder = 0;
                    var c3LastOrder = 0;
                    for (var i = 0; i < theWidgets.length; i++) {
                        if (theWidgets[i].obj.ColumnNo == 1) {
                            if (c1LastOrder < theWidgets[i].obj.OrderNo)
                                c1LastOrder = theWidgets[i].obj.OrderNo;
                        }
                        else if (theWidgets[i].obj.ColumnNo == 2) {
                            if (c2LastOrder < theWidgets[i].obj.OrderNo)
                                c2LastOrder = theWidgets[i].obj.OrderNo;
                        }
                        else if (theWidgets[i].obj.ColumnNo == 3) {
                            if (c3LastOrder < theWidgets[i].obj.OrderNo)
                                c3LastOrder = theWidgets[i].obj.OrderNo;
                        }
                    }

                    /*
                    _Tab.Element_Cell1 -> Widget Column1
                    _Tab.Element_Cell2 -> Widget Column2
                    _Tab.Element_Cell3 -> Widget Column3
                    */

                    //Time to move the widgets
                    var Movement = "";
                    for (var i = 0; i < theWidgets.length; i++) {
                        var theWidget = theWidgets[i];
                        if (c2To > 0 && theWidget.obj.ColumnNo == 2) {
                            theWidget.obj.OrderNo = ++c1LastOrder;
                            this.MoveWidgetToColumn(Tab, theWidget, c2To);
                        }
                        else if (c3To > 0 && theWidget.obj.ColumnNo == 3) {
                            switch (c3To) {
                                case 2:
                                    theWidget.obj.OrderNo = ++c2LastOrder;
                                    break;
                                case 1:
                                    theWidget.obj.OrderNo = ++c1LastOrder;
                                    break;
                            }
                            this.MoveWidgetToColumn(Tab, theWidget, c3To);
                        }
                        else if (c4To > 0 && theWidget.obj.ColumnNo == 4) {
                            switch (c4To) {
                                case 3:
                                    theWidget.obj.OrderNo = ++c3LastOrder;
                                    break;
                                case 2:
                                    theWidget.obj.OrderNo = ++c2LastOrder;
                                    break;
                                case 1:
                                    theWidget.obj.OrderNo = ++c1LastOrder;
                                    break;
                            }
                            this.MoveWidgetToColumn(Tab, theWidget, c4To);
                        }
                    }

                    //now all the widgets are in the correct place, get their orders in
                    var C1ID = "";
                    var C2ID = "";
                    var C3ID = "";
                    var C4ID = "";

                    var Nodes = Tab.Element_Cell1.childNodes
                    for (var i = 0; i < Nodes.length; i++) {
                        var theDivId = Nodes[i].id;
                        if (theDivId.length > 5) {
                            var WidgetInstanceID = parseInt(theDivId.substring(5));
                            //must be int based on the format
                            if (WidgetInstanceID > 0)
                                C1ID += WidgetInstanceID + ",";
                        }
                    }

                    Nodes = Tab.Element_Cell2.childNodes;
                    for (var i = 0; i < Nodes.length; i++) {
                        var theDivId = Nodes[i].id;
                        if (theDivId.length > 5) {
                            var WidgetInstanceID = parseInt(theDivId.substring(5));
                            //must be int based on the format
                            if (WidgetInstanceID > 0)
                                C2ID += WidgetInstanceID + ",";
                        }
                    }

                    Nodes = Tab.Element_Cell3.childNodes;
                    for (var i = 0; i < Nodes.length; i++) {
                        var theDivId = Nodes[i].id;
                        if (theDivId.length > 5) {
                            var WidgetInstanceID = parseInt(theDivId.substring(5));
                            //must be int based on the format
                            if (WidgetInstanceID > 0)
                                C3ID += WidgetInstanceID + ",";
                        }
                    }

                    if (Tab.Element_Cell4) {
                        Nodes = Tab.Element_Cell4.childNodes;
                        for (var i = 0; i < Nodes.length; i++) {
                            var theDivId = Nodes[i].id;
                            if (theDivId.length > 5) {
                                var WidgetInstanceID = parseInt(theDivId.substring(5));
                                //must be int based on the format
                                if (WidgetInstanceID > 0)
                                    C4ID += WidgetInstanceID + ",";
                            }
                        }
                    }

                    //Update Database
                    JSON.Tab_UpdateWidgetOrder(Tab.id, 1, C1ID);
                    JSON.Tab_UpdateWidgetOrder(Tab.id, 2, C2ID);
                    JSON.Tab_UpdateWidgetOrder(Tab.id, 3, C3ID);
                    JSON.Tab_UpdateWidgetOrder(Tab.id, 4, C4ID);

                    //sort the widget array just to be safe..
                    myWidgets.SortWidgetArray(Tab);
                }
            }
        }
        else {
            alert("You do not have permission to change layout of the page");
        }
    },

    MoveWidgetToColumn: function(Tab, Widget, Column) {
        if (this.hasRequiredTabPermission(Tab, TabAccessLevel.Widget_Reorder)) {
            WriteHistory("MoveWidgetToColumn: " + Tab.id + " : " + Widget.id + " : " + Column + " : " + Widget.obj.ColumnNo);
            var RenderInColumn = null;
            var RemoveFromColumn = null;
            switch (Column) {
                case 2:
                    RenderInColumn = Tab.Element_Cell2;
                    break;
                case 3:
                    RenderInColumn = Tab.Element_Cell3;
                    break;
                case 4:
                    RenderInColumn = Tab.Element_Cell4;
                    break;
                case 1:
                    RenderInColumn = Tab.Element_Cell1;
                    break;
            }

            switch (Widget.obj.ColumnNo) {
                case 2:
                    RemoveFromColumn = Tab.Element_Cell2;
                    break;
                case 3:
                    RemoveFromColumn = Tab.Element_Cell3;
                    break;
                case 4:
                    RemoveFromColumn = Tab.Element_Cell4;
                    break;
                case 1:
                    RemoveFromColumn = Tab.Element_Cell1;
                    break;
            }

            if (!RenderInColumn) {
                WriteHistory("RenderInColumn is null: " + Column);
            }

            if (!RemoveFromColumn) {
                WriteHistory("RemoveFromColumn is null: " + Widget.obj.ColumnNo);
            }

            //first have to remove from original column
            WriteHistory("RemoveFromColumn: " + RemoveFromColumn.id + ":" + Widget.instance.WidgetDiv.id + ":" + Widget.obj.Title + " : MoveTo: " + RenderInColumn.id);
            //WriteHistory(Widget.instance.WidgetDiv);
            RemoveFromColumn.removeChild(Widget.instance.WidgetDiv);

            Widget.obj.ColumnNo = Column;
            if (RenderInColumn.childNodes.length <= Widget.obj.OrderNo) {
                RenderInColumn.appendChild(Widget.instance.WidgetDiv);
            }
            else {
                RenderInColumn.insertBefore(Widget.instance.WidgetDiv, RenderInColumn.childNodes[Widget.obj.OrderNo - 1]);
            }
        }
        else {
            alert("You do not have permission to reorder widgets");
        }
    },

    EnableDragDrop: function() {
        Sortable.destroy(div_TabList.id);
        Sortable.create(div_TabList.id,
      {
          overlap: 'horizontal',
          dropOnEmpty: false,
          containment: [div_TabList.id],
          constraint: 'horizontal',
          onUpdate: function(sortable) {
              if (sortable.id) {
                  var Elements = sortable.getElementsByTagName("li");
                  var TabIds = "";
                  for (var i = 0; i < Elements.length; i++) {
                      var TabId = parseInt(Elements[i].id.substring(2));

                      TabIds += TabId + ",";
                  }
                  WriteHistory("TabOnUpdate: " + TabIds);
                  JSON.Tab_UpdatePosition(TabIds);
              }
          } /*,
         onChange:function(element){
            //WriteHistory("onChange<br>" + Sortable.serialize(element.parentNode));
         }*/
      });
    },

    EnableWidgetDragDrop: function(Tab, Col) {
        if (this.hasRequiredTabPermission(Tab, TabAccessLevel.Widget_Reorder)) {
            var strCol = "";
            switch (Col) {
                case 2:
                    strCol = Tab.Element_Cell2.id;
                    break;
                case 3:
                    strCol = Tab.Element_Cell3.id;
                    break;
                case 4:
                    if (Tab.Element_Cell4)
                        strCol = Tab.Element_Cell4.id;
                    else
                        strCol = Tab.Element_Cell1.id;
                    break;
                default:
                    strCol = Tab.Element_Cell1.id;
                    break;
            }

            var Containment = [Tab.Element_Cell1.id, Tab.Element_Cell2.id, Tab.Element_Cell3.id];

            if (Tab.Element_Cell4)
                Containment = [Tab.Element_Cell1.id, Tab.Element_Cell2.id, Tab.Element_Cell3.id, , Tab.Element_Cell4.id];

            WriteHistory("EnableWidgetDragDrop: " + Tab.id + ":" + Col);
            Sortable.destroy(strCol);
            Sortable.create(strCol,
         {
             tag: 'div',
             only: 'widget',
             constraint: false,
             containment: Containment,
             handle: 'widget_header',
             hoverclass: 'widget_hover',
             dropOnEmpty: true,
             onUpdate: function(sortable) {
                 WriteHistory("onUpdate<br>" + sortable.id);
                 if (sortable.id) {
                     var Widgets = "";
                     var Tab = myTabs.GetCurrentTab();
                     //c[tabid]_[col]
                     var Col = parseInt(sortable.id.substring(2 + Tab.id.toString().length));
                     var Elements = new Array();
                     for (var i = 0; i < sortable.childNodes.length; i++) {
                         var Node = sortable.childNodes[i];
                         if (Node.className == "widget")
                             Elements.push(Node);
                     }

                     for (var i = 0; i < Elements.length; i++) {
                         var WidgetId = parseInt(Elements[i].id.substring(5));
                         //Update Widget Order
                         var theWidget = Tab.FindWidget(WidgetId);
                         theWidget.obj.ColumnNo = Col;
                         theWidget.obj.OrderNo = i + 1;

                         Widgets += WidgetId + ",";
                     }

                     //Save Order
                     WriteHistory("WidgetsOnUpdate: " + Widgets + ":" + Col);
                     JSON.Tab_UpdateWidgetOrder(Tab.id, Col, Widgets);
                 }
             }
         });
        }
        else {
            alert("You do not have permission to reorder widgets");
        }
    }
};

var myTabs = new _myTabs();

//tab_scroll_L, tab_scroll_R
var tab_tout=null;
var tab_width=0;
var tab_speed = 5;
var tab_spacer = 200;
function right(){
if(!div_TabList.style.marginLeft){ marg = 0; } else {
marg = parseInt(div_TabList.style.marginLeft); }
marg -= tab_speed;
   
if(parseInt(tab_width+marg)>parseInt(div_tabHolder.clientWidth)){
div_TabList.style.marginLeft = marg + "px";
div_TabList.style.width = (tab_spacer+parseInt(div_tabHolder.style.width)-marg)+ "px";
}
tab_tout = setTimeout("right()",0);
}

function left(){
if(!div_TabList.style.marginLeft){ marg = 0; } else {
marg = parseInt(div_TabList.style.marginLeft); }
if(marg < 0){
marg += tab_speed;

   
WriteHistory("L: " + div_TabList.style.marginLeft);
div_TabList.style.marginLeft = marg + "px";
div_TabList.style.width = (tab_spacer+parseInt(div_tabHolder.style.width)-marg)+ "px";
tab_tout = setTimeout("left()",0);
}
}

function pause(){
clearTimeout(tab_tout)
}